package cz.fimuni.pa165.restfrontend;

import com.google.gson.Gson;
import cz.fimuni.pa165.backendapi.dto.CompanyDTO;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

/**
 *
 * @author Lukáš Slovák
 */

@Controller
public class CompanyController {
    
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private Gson gson;
    
    @RequestMapping(value="/companies")
    public String companyHome(Model model){
        try{
            String result = restTemplate.getForObject("http://localhost:8080/pa165/rest/company/all", String.class);
            List<CompanyDTO> list = gson.fromJson(result, List.class);
            model.addAttribute("companies", list);
        }catch (HttpClientErrorException e) {
            if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                return error("Server nedostupný", model);
            }
        }catch (ResourceAccessException e) {
                return error("Server nedostupný(spojenie odmietnuté)", model);
        }
        return "company/list";
    }
       
    @RequestMapping(value="/companyAdd")
    public String addCompany(@RequestParam(value="input1") String input1,
                             @RequestParam(value="input2") String input2,
                             Model model){
        boolean somethingIsMissing = false;
        input1 = input1.trim();
        input2 = input2.trim();
        if (input1.equals("")){
            somethingIsMissing = true;
        }
        if (input2.equals("")){
            somethingIsMissing = true;
        }
        if (!somethingIsMissing){
            try {
                CompanyDTO comp = new CompanyDTO();
                comp.setName(input1);
                comp.setAdress(input2);
                String json = gson.toJson(comp);
                HttpHeaders headers = new HttpHeaders();
                headers.add("Content-Type", "application/json; charset=utf-8");

                HttpEntity RESTrequest = new HttpEntity(json, headers);
                restTemplate.postForLocation("http://localhost:8080/pa165/rest/company/add", RESTrequest);
            } catch (HttpClientErrorException e) {
                if (e.getStatusCode() == HttpStatus.BAD_REQUEST) {
                    return error("Nepodarilo sa pridať. Daná firma už existuje", model);
                }
                if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                    return error("Server nedostupný", model);
                }
            }catch (ResourceAccessException e) {
                return error("Server nedostupný(spojenie odmietnuté)", model);
            }
        }
           
        return "redirect:/companies";
    }
    
    @RequestMapping(value="/companyDelete/{id}")
    public String deleteCompany(@PathVariable(value="id") String id,
                                Model model){
        try{
        restTemplate.delete("http://localhost:8080/pa165/rest/company/delete/" + id, String.class);
        }catch (HttpClientErrorException e) {
            if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
                return error("Nepodarilo sa zmazať. Chyba databázy", model);
            }
            if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                    return error("Server nedostupný", model);
            }
        }catch (ResourceAccessException e) {
                return error("Server nedostupný(spojenie odmietnuté)", model);
        }
        return "redirect:/companies";
    }
    
    @RequestMapping(value="/companyEditJSP/{id}")
    public String companyEditJSP(@PathVariable(value="id") String id,
                                 Model model){
        try{
            String comp = new RestTemplate().getForObject("http://localhost:8080/pa165/rest/company/get/" + id, String.class);
            CompanyDTO compDTO = gson.fromJson(comp, CompanyDTO.class);
            model.addAttribute("company", compDTO);
        }catch (HttpClientErrorException e) {
            if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                return error("Server nedostupný", model);
            }
        }catch (ResourceAccessException e) {
                return error("Server nedostupný(spojenie odmietnuté)", model);
        }
        return "company/edit";
    }
    
    @RequestMapping(value="/companyEdit")
    public String companyEdit(@RequestParam(value="id") String id,
                              @RequestParam(value="name") String name,
                              @RequestParam(value="adress") String adress,
                              Model model){
        boolean somethingIsMissing = false;
        name = name.trim();
        adress = adress.trim();
        if (name.equals("")){
            somethingIsMissing = true;
        }
        if (adress.equals("")){
            somethingIsMissing = true;
        }
        if (!somethingIsMissing){
            CompanyDTO comp = new CompanyDTO();
            comp.setId(new Long(id));
            comp.setName(name);
            comp.setAdress(adress);
            String json = gson.toJson(comp);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/json; charset=utf-8");
            HttpEntity RESTrequest = new HttpEntity(json, headers);
            try {
                restTemplate.postForLocation("http://localhost:8080/pa165/rest/company/edit", RESTrequest);
            } catch (HttpClientErrorException e) {
                if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                    return error("Server nedostupný", model);
                }
                if (e.getStatusCode() == HttpStatus.BAD_REQUEST) {
                    return error("Nepodarilo sa upraviť. Už existuje iná firma s tým istým menom", model);
                }
            }catch (ResourceAccessException e) {
                return error("Server nedostupný(spojenie odmietnuté)", model);
            }
        }else{
            return "redirect:/companyEditJSP/"+id;
        }
        return "redirect:/companies";
    }
    
    public String error(String message,
                        Model model){
        model.addAttribute("errMessage", message);
        return "company/companyError";
    }
}